package org.imraniqbal.engine;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;

/**
 * @author  imran
 */
public class GameController<G extends Game> extends KeyAdapter implements ActionListener{
	/**
	 * @author   imran
	 */
	public enum Controls{/**
	 * @uml.property  name="uP"
	 * @uml.associationEnd  
	 */
	UP, /**
	 * @uml.property  name="dOWN"
	 * @uml.associationEnd  
	 */
	DOWN, /**
	 * @uml.property  name="lEFT"
	 * @uml.associationEnd  
	 */
	LEFT, /**
	 * @uml.property  name="rIGHT"
	 * @uml.associationEnd  
	 */
	RIGHT, /**
	 * @uml.property  name="aCTION"
	 * @uml.associationEnd  
	 */
	ACTION};
	
	/**
	 * @uml.property  name="g"
	 * @uml.associationEnd  
	 */
	private Game g;
	/**
	 * @uml.property  name="gp"
	 * @uml.associationEnd  
	 */
	private GamePanel<? extends Game> gp;
	
	private Memory<G> gameMemory;
	/**
	 * Create a controller for the game
	 * @param g the game you want a controller for
	 */
	public GameController(Game g, GamePanel<? extends Game> gp){
		this.g = g;
		this.gp = gp;
		gameMemory = new Memory<G>();
	}
	/**
	 * Sends the game a control bases on keyboard input
	 */
	@Override
	public void keyPressed(KeyEvent e){
		switch(e.getKeyCode()){
		case KeyEvent.VK_UP:
			g.getControl(Controls.UP, gameMemory);
			break;
		case KeyEvent.VK_DOWN:
			g.getControl(Controls.DOWN, gameMemory);
			break;
		case KeyEvent.VK_LEFT:
			g.getControl(Controls.LEFT, gameMemory);
			break;
		case KeyEvent.VK_RIGHT:
			g.getControl(Controls.RIGHT,gameMemory) ;
			break;
		case KeyEvent.VK_SPACE:
			g.getControl(Controls.ACTION, gameMemory);
			break;
		}
		gp.repaint();
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		G game = null;
		try {
			String s = e.getActionCommand();
			if(s == "Undo"){
				game = gameMemory.undo();
			}else if( s == "Redo"){
				game = gameMemory.redo();
			}
		
			if(game != null){
				this.g = game;
				gp.setGame(game);
				gp.repaint();
			}
		
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
		
	}
}
